package thomas.bier.server;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import thomas.bier.shared.Gebruiker;

public class GebruikerJPAImpl implements GebruikerJPA {

	@Override
	public Gebruiker login(String nickname, String ww) {
		EntityManager em = PersistenceManager.get().createEntityManager();
		Query query = em.createQuery("SELECT g FROM Gebruiker g WHERE g.nickname = ?");
		query.setParameter(1, nickname);
		Gebruiker result = (Gebruiker) query.getSingleResult();
		if(result!= null){
			if(BCrypt.checkpw(ww, result.getWw())){
				return result;
			}
		}
		em.close();
		return null;
	}

	@Override
	public boolean register(Gebruiker g) {
		g.setWw(BCrypt.hashpw(g.getWw(), BCrypt.gensalt()));
		EntityManager em = PersistenceManager.get().createEntityManager();
		try{
			em.persist(g);			
		}
		catch(PersistenceException e){
			System.out.println("Error in register: "+e.toString());
			return false;			
		}
		finally {
			em.close();
		}
		return true;
	}	
}
